import { createRouter, createWebHistory } from "vue-router";
import axios from "axios";
// eslint-disable-next-line no-unused-vars
import store from "@/store";
import HomeView from "../views/HomeView.vue";
import NetworkdiskView from "../views/NetworkdiskView.vue";
import LoginView from "../views/LoginView.vue";
import RegisterView from "../views/RegisterView.vue";
import DocumentView from "@/views/DocumentView.vue";

const routes = [
  {
    path: "/",
    name: "home",
    mate: { title: "霸霸网盘-首页" },
    component: HomeView,
  },
  {
    path: "/login",
    name: "LoginView",
    component: LoginView,
    meta: { requiresAuth: false, title: "霸霸网盘-登录" },
  },
  {
    path: "/register",
    name: "register",
    component: RegisterView,
    meta: { requiresAuth: false, title: "霸霸网盘-注册" },
  },
  {
    path: "/networkdisk",
    name: "networkdisk",
    component: NetworkdiskView,
    meta: { requiresAuth: true, title: "霸霸网盘-网盘" },
  },
  {
    path: "/home",
    name: "HomeView",
    component: HomeView,
    meta: { requiresAuth: false, title: "霸霸网盘-首页" },
  },
  {
    path: "/document",
    name: "DocumentView",
    component: DocumentView,
    meta: { requiresAuth: true, title: "霸霸网盘-文档" },
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 假设有一个函数用于发送请求到服务器验证session
function checkSession() {
  // 从本地存储中获取token
  const token = sessionStorage.getItem("auth_token");

  // 如果没有token，直接返回false
  if (!token) {
    console.log("没有token");
    return Promise.reject(new Error("没有token"));
  }

  // 发送一个请求到服务器验证token
  return (
    axios
      .get("/api/session", {})
      // eslint-disable-next-line no-unused-vars
      .then((response) => {
        // 如果验证成功，返回true
        return true;
      })
      // eslint-disable-next-line no-unused-vars
      .catch((error) => {
        // 如果验证失败或请求出错，返回false或抛出错误
        return false; // 或者你可以抛出错误并捕获它来处理登录或重定向逻辑
      })
  );
}

// 添加路由守卫
// eslint-disable-next-line no-unused-vars
router.beforeEach((to, from, next) => {
  // 检查路由是否需要验证
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth);
  if (!requiresAuth) {
    // 如果不需要验证，直接通过
    return next();
  }
  // 检查session是否有效
  checkSession()
    .then((isValid) => {
      if (isValid) {
        // session有效，允许继续导航
        next();
      } else {
        // session无效，重定向到登录页面或执行其他逻辑
        next({
          path: "/login",
          query: { redirect: to.fullPath },
        });
      }
    })
    .catch((error) => {
      // 处理请求错误，可能需要重定向到错误页面或重新尝试登录
      console.error("会话验证失败,session失效请重新登录：", error);
      next("/login"); // 或者其他适当的重定向路径
    });
});

// 设置页面标题
router.beforeEach((to, from, next) => {
  to.meta.title && (document.title = to.meta.title);
  next();
});

export default router;
